package dialogs.ranking;

import java.util.ArrayList;

import javax.swing.event.TableModelEvent;
import javax.swing.table.AbstractTableModel;

import persistence.Game;
import persistence.Player;

@SuppressWarnings("serial")
public class RankingTableModel extends AbstractTableModel{
	
	private ArrayList<Player> players;
	private ArrayList<Game> games;
	
	private String[] columnNames = {"Spieler",
            "Spiele",
            "gewonnene Spiele",
            "Tore/Spiel"};
	
	public void setPlayers(ArrayList<Player> players) {
		this.players = players;
		// JTable benachrichtigen
		this.fireTableChanged(new TableModelEvent(this));
	}
	public void setGames(ArrayList<Game> games) {
		this.games=games;
		// JTable benachrichtigen
		this.fireTableChanged(new TableModelEvent(this));
	}
	/**
	 *  Abfrage der Spaltennamen
	 *
	 * @see javax.swing.table.TableModel#getColumnName(int)
	 */
	@Override
	public String getColumnName(int columnIndex) {
		return columnNames[columnIndex];
	}
	
	@Override
	public int getColumnCount() {		
		return columnNames.length;
	}

	@Override
	public int getRowCount() {
		return players.size();
	}
	
	public boolean containsPlayer(Player player) {
		return players.contains(player);
	}
	public boolean containsGame(Game game) {
		return players.contains(games);
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		Object date = null;  
		Player player = players.get(rowIndex);
		int count = 0;
		switch (columnIndex) {
		case 0:
			date = player.toString();
			break;
		case 1:
			for (Game game : games) {
				if(game.isInGame(player))
					count++;
			}
			date = count;
			break;
		case 2:
			for (Game game : games) {
				if(game.isWon(player))
					count++;
			}
			date = count;
			break;
		case 3:
			int goals = 0;
			for (Game game : games) {
				if(game.isInGame(player)) {
					goals += game.getStatsGoals(player);
					count++;
				}
					
			}
			if(count!=0) 
				date = (double)goals/count; 
			else
				date = (double)0;
			break;
		}
		return date;
	}
	public void addGame(Game game) {
		games.add(game);
		this.fireTableChanged(new TableModelEvent(this));
	}
	public void addPlayer(Player player) {
		players.add(player);
		this.fireTableChanged(new TableModelEvent(this));
	}
	

}
